<template src="./template.html"></template>

<style src="./style.css" scoped></style>

<script>
    import giftBg from '../assets/images/package-bg.png';
    import getGiftImg from '../assets/images/btn-get.png';
    import api from 'api/api';
    import modal from 'utils/modal';
    import navigator from 'utils/navigator';
    import route from 'constants/route';
    import constant from 'constants/constant';

    export default{
        data(){
            return{
                fromType: "fridge",
                giftBg: giftBg,
                getGiftImg: getGiftImg,
                giftTip: "输入激活码可领取大礼包，如有疑问，请联系客服：0551-62214496。", //默认值
                giftValue: "",
                listLoaded: false
            }
        },
        created(){
            api.sendHttp("getBindMyCodeDesApi",{}).then(res=>{
                let _code = res.data;
                if(_code) this.giftTip = _code;
                this.listLoaded = true;
            },res=>{
                modal.toast(res.msg);
            })
        },
        methods: {
            getGift(){
                let self = this;
                if(self.checkInput()){
                    let _coupon = self.giftValue.replace(/\s/g,"");
                    let options = {
                        coupon: _coupon,
                        fromtype: this.fromType
                    };
                    api.sendHttp("bindMyCodeApi",options).then(res=>{
                        navigator.pop(); //关闭当前弹框

                        let options = {
                            classType: constant.Activity_Class_Type,
                            url: route.my_gift_bind,
                            params: {
                                gift: res.data || {}
                            }
                        };
                        navigator.push(options);
                    },res=>{
                        modal.toast(res.msg || "绑定激活码失败");
                        this.$refs['gift_input'].blur(); //隐藏键盘
                    });
                }
            },
            checkInput(){
                let self = this;
                if(!self.giftValue) {
                    modal.toast("请输入激活码");
                    return false;
                }
                if(self.giftValue.replace(/\s/g,"").length != 12) {
                    modal.toast("激活码长度有误");
                    return false;
                }
                if(!/^[0-9a-zA-Z]*$/g.test(self.giftValue.replace(/\s/g,""))) {
                    modal.toast("激活码只能输入数字或字母");
                    return false;
                }
                return true;
            },
            oninput(event){
                let self = this;
                let v = event.value;
                if(/\S{5}/.test(v)){
                    self.giftValue = v.replace(/\s/g, '').replace(/(.{4})/g, "$1 ").substr(0,14);
                }
            }
        }
    }
</script>
